<?php

//用户前端区块展示，数据源不用再走控制器
//模型内查询，单关联，多关联
//mlist('cat','*',array('id'=>array(9,10)),array('imgs|m'=>'images:id,path'));
//mlist('cat','*',array('id'=>array(9,10)),array('img_id|s'=>'images:id,path'));
function mlist($tbl_name,$col = '*',$filter=array(),$link = array(),$from=0,$pagesize=0,$ord='',$rt='o'){
	$CI =&get_instance();

	$CI->db->from($tbl_name);
	foreach ($filter as $k => $v) {
		if(is_array($v)){
			$CI->db->where_in($k,$v);
		}else{

			if($filter_type = strstr($k,'|')){

				$t = explode('|', $k);
				$k = $t[0];

				$filter_type = trim($filter_type,'|');
				if($filter_type == 'l'){
					$CI->db->like($k,$v);
				}elseif($filter_type == 'lb'){
					$CI->db->like($k,'%'.$v);
				}elseif($filter_type == 'la'){
					$CI->db->like($k,$v.'%');
				}
			}else{
				$CI->db->where($k,$v);
			}

		}
	}

	if($pagesize>0) $CI->db->limit($pagesize,$from);

	$query = $CI->db->get();
	$list = $query->result_array();

	if(empty($list)) return array();
	if(empty($link)){
		if($rt == 'o'){
			return json_decode(json_encode($list));
		}else{
			return $list;
		}
	} 

	foreach ($link as $k => $v) {

		$t = explode('|',$k);
		$col = $t[0];//主字段
		$link_type = $t[1]; //连接类型，单连接还是多连接
		$arr_link_id = array();//关联ID
		foreach ($list as $kk => $vv) {
			if($link_type == 'm'){
				$arr_link_id = array_merge($arr_link_id,explode(',', $vv[$col]));
			}elseif($link_type == 's'){
				$arr_link_id[] = $vv[$col];
			}
		}

		$arr_link_id = array_unique($arr_link_id);

		$t = explode(':', $v);
		$link_tbl = $t[0];//关联表
		$arr_link_col = explode(',', $t[1]);
		$key_col = $arr_link_col[0];//关联字段
		$CI->db->from($link_tbl);
		$CI->db->where_in($key_col,$arr_link_id);
		$query = $CI->db->get();
		$link_list = $query->result_array();

		foreach ($link_list as $kk => $vv) {
			$link_list[$vv[$key_col]] = $vv;
			unset($link_list[$kk]);
		}

		foreach ($list as $kk => $vv) {
			
			if($link_type == 'm'){
				$vv[$col]  = trim($vv[$col],',');
				$t = explode(',', $vv[$col]);
				foreach ($t as $kkk => $vvv) {
					if(array_key_exists($vvv, $link_list)){
						$list[$kk][$col.'_list'][] = $link_list[$vvv];		
					}
				}
			}elseif($link_type == 's'){
				if(array_key_exists($vv[$col], $link_list)){
					$list[$kk][$col.'_row'] = $link_list[$vv[$col]];
				}
			}
		}

	}

	if($rt == 'o'){
		return json_decode(json_encode($list));
	}

	return $list;
}

function block($name){
	$CI =&get_instance();

	$CI->db->from('block');
	$CI->db->where('name',$name);

	$query = $CI->db->get();
	$list = $query->result_array();
	return $list[0]['cont'];
}

?>
